``
<template>
  <view class="page">
    <view class="card">
      <up-cell-group>
        <!-- 头像选择项 -->
        <up-cell :custom-style="cellStyle" center @click="changeAvatar">
          <template #title>
            <view class="title-fixed">头像</view>
          </template>
          <template #value>
            <view class="avatar-cell">
              <up-avatar :src="form.headerImg || defaultAvatar" size="60"></up-avatar>
            </view>
          </template>
        </up-cell>

        <up-cell :custom-style="cellStyle" center>
          <template #title>
            <view class="title-fixed">昵称</view>
          </template>
          <template #value>
            <up-input
              v-model.trim="form.nickName"
              placeholder="请输入昵称"
              placeholder-style="color:#c0c4cc"
              border="none"
              clearable
              input-align="left"
              :custom-style="inputStyle"
            />
          </template>
        </up-cell>
        <up-cell :is-link="true" center :custom-style="cellStyle" @click="openSchoolPicker">
          <template #title>
            <view class="title-fixed">学校</view>
          </template>
          <template #value>
            <view
              :class="[
                'cell-value',
                form.schoolName ? 'cell-value--filled' : 'cell-value--placeholder',
              ]"
            >
              {{ form.schoolName || '请选择学校' }}
            </view>
          </template>
        </up-cell>
        <up-cell :is-link="true" center :custom-style="cellStyle" @click="showGradePicker = true">
          <template #title>
            <view class="title-fixed">年级</view>
          </template>
          <template #value>
            <view
              :class="[
                'cell-value',
                form.gradeName ? 'cell-value--filled' : 'cell-value--placeholder',
              ]"
            >
              {{ form.gradeName || '请选择年级' }}
            </view>
          </template>
        </up-cell>

        <up-cell :is-link="true" center :custom-style="cellStyle" @click="showMajorPicker = true">
          <template #title>
            <view class="title-fixed">专业</view>
          </template>
          <template #value>
            <view
              :class="[
                'cell-value',
                form.majorName ? 'cell-value--filled' : 'cell-value--placeholder',
              ]"
            >
              {{ form.majorName || '请选择专业' }}
            </view>
          </template>
        </up-cell>
        <up-cell
          :is-link="true"
          center
          :custom-style="cellStyle"
          @click="showEducationPicker = true"
        >
          <template #title>
            <view class="title-fixed">学历</view>
          </template>
          <template #value>
            <view
              :class="[
                'cell-value',
                form.educationName ? 'cell-value--filled' : 'cell-value--placeholder',
              ]"
            >
              {{ form.educationName || '请选择学历' }}
            </view>
          </template>
        </up-cell>
        <up-cell :custom-style="cellStyle" center>
          <template #title>
            <view class="title-fixed">手机号</view>
          </template>
          <template #value>
            <up-input
              v-model.trim="form.phone"
              placeholder="请输入手机号"
              placeholder-style="color:#c0c4cc"
              border="none"
              clearable
              input-align="left"
              :custom-style="inputStyle"
              type="number"
            />
          </template>
        </up-cell>
        <up-cell :custom-style="cellStyle" center>
          <template #title>
            <view class="title-fixed">邮箱</view>
          </template>
          <template #value>
            <up-input
              v-model.trim="form.email"
              placeholder="请输入邮箱"
              placeholder-style="color:#c0c4cc"
              border="none"
              clearable
              input-align="left"
              :custom-style="inputStyle"
            />
          </template>
        </up-cell>

        <up-cell :custom-style="cellStyle" center>
          <template #title>
            <view class="title-fixed">签名</view>
          </template>
          <template #value>
            <up-textarea
              v-model.trim="form.signature"
              placeholder="介绍一下自己吧"
              placeholder-style="color:#c0c4cc"
              maxlength="50"
              count
              auto-height
              :custom-style="textareaStyle"
              border="none"
            />
          </template>
        </up-cell>
      </up-cell-group>
    </view>

    <view class="footer">
      <up-button
        type="primary"
        :custom-style="btnStyle"
        shape="circle"
        :loading="saving"
        @click="showSaveDialog"
        >保存</up-button
      >
    </view>

    <!-- 学校选择器 -->
    <up-picker
      :show="showSchoolPicker"
      :columns="[schoolOptions]"
      @confirm="onConfirmSchool"
      @cancel="showSchoolPicker = false"
      @close="showSchoolPicker = false"
    />

    <!-- 专业选择器 -->
    <up-picker
      :show="showMajorPicker"
      :columns="[majorOptions]"
      @confirm="onConfirmMajor"
      @cancel="showMajorPicker = false"
      @close="showMajorPicker = false"
    />

    <!-- 年级选择器 -->
    <up-picker
      :show="showGradePicker"
      :columns="[gradeOptions]"
      @confirm="onConfirmGrade"
      @cancel="showGradePicker = false"
      @close="showGradePicker = false"
    />

    <!-- 学历选择器 -->
    <up-picker
      :show="showEducationPicker"
      :columns="[educationOptions]"
      @confirm="onConfirmEducation"
      @cancel="showEducationPicker = false"
      @close="showEducationPicker = false"
    />
  </view>
</template>
<script setup>
  import { ref } from 'vue';
  import { onLoad, onUnload } from '@dcloudio/uni-app';
  import { put, get } from '@/utils/request';

  const defaultAvatar = '/static/images/logo.jpg';

  /**
   * 表单数据
   * 字段与后端 /c/user/setSelfInfo 的入参保持一致
   */
  const form = ref({
    id: null, // 用户ID (必传)
    nickName: '', // 昵称 (必传)
    phone: '', // 手机号 (必传)
    email: '', // 邮箱 (必传)
    headerImg: '', // 头像 (必传)
    grade: null, // 年级 (必传)
    school: null, // 学校ID (必传)
    major: null, // 专业ID (必传)
    education: null, // 学历 (必传)
    signature: '', // 签名 (必传)
    // 显示用的字段
    schoolName: '', // 学校名称显示
    majorName: '', // 专业名称显示
    gradeName: '', // 年级名称显示
    educationName: '', // 学历名称显示
  });

  const saving = ref(false);
  const btnStyle = {
    width: '100%',
    height: '88rpx',
    borderRadius: '44rpx',
  };

  const cellStyle = {
    padding: '24rpx 28rpx',
  };
  const inputStyle = {
    fontSize: '32rpx',
  };
  const textareaStyle = {
    background: '#f7f8fa',
    padding: '20rpx',
    borderRadius: '12rpx',
    fontSize: '32rpx',
    lineHeight: '1.6',
  };

  // 预填用户信息的处理函数
  const handlePrefillUser = userData => {
    if (userData && typeof userData === 'object') {
      // 预填充表单数据
      Object.keys(userData).forEach(key => {
        if (Object.prototype.hasOwnProperty.call(form.value, key)) {
          form.value[key] = userData[key];
        }
      });
    }
  };

  // 从上一页通过 eventChannel 预填用户信息
  onLoad(async () => {
    // 监听用户信息预填充事件
    uni.$on('prefillUser', handlePrefillUser);

    try {
      await Promise.all([fetchSchools(), fetchMajors(), fetchGrades(), fetchEducations()]);
    } catch (e) {
      console.warn('prefillUser channel error:', e);
    }
  });

  // 页面卸载时清理事件监听器
  onUnload(() => {
    uni.$off('prefillUser', handlePrefillUser);
  });

  // 学校、专业、年级、学历选择器相关数据
  const showSchoolPicker = ref(false);
  const showMajorPicker = ref(false);
  const showGradePicker = ref(false);
  const showEducationPicker = ref(false);
  const schoolOptions = ref([]);
  const majorOptions = ref([]);
  const gradeOptions = ref([]);
  const educationOptions = ref([]);

  // 打开学校选择器
  const openSchoolPicker = () => {
    if (!schoolOptions.value || schoolOptions.value.length === 0) {
      fetchSchools().then(() => {
        if (schoolOptions.value && schoolOptions.value.length > 0) {
          showSchoolPicker.value = true;
        } else {
          uni.showToast({ title: '获取学校数据失败', icon: 'none' });
        }
      });
    } else {
      showSchoolPicker.value = true;
    }
  };

  // 学校选择确认
  const onConfirmSchool = e => {
    const selected = e?.value?.[0];
    if (selected) {
      form.value.schoolName = selected.text || selected.label || selected;
      form.value.school = selected.value; // value已经是数字类型
    }
    showSchoolPicker.value = false;
  };

  // 专业选择确认
  const onConfirmMajor = e => {
    const selected = e?.value?.[0];
    if (selected) {
      form.value.majorName = selected.text || selected.label || selected;
      form.value.major = selected.value; // value已经是数字类型
    }
    showMajorPicker.value = false;
  };

  // 年级选择确认
  const onConfirmGrade = e => {
    const selected = e?.value?.[0];
    if (selected) {
      form.value.gradeName = selected.text || selected.label || selected;
      form.value.grade = selected.value; // value已经是数字类型
    }
    showGradePicker.value = false;
  };

  // 学历选择确认
  const onConfirmEducation = e => {
    const selected = e?.value?.[0];
    if (selected) {
      form.value.educationName = selected.text || selected.label || selected;
      form.value.education = selected.value; // value已经是数字类型
    }
    showEducationPicker.value = false;
  };

  // 获取学校列表
  const fetchSchools = async () => {
    try {
      const response = await get('/sysDictionaryDetail/getSysDictionaryDetailList', {
        page: 1,
        pageSize: 200,
        sysDictionaryID: 10,
      });

      if (response && response.code === 0 && Array.isArray(response.data?.list)) {
        schoolOptions.value = response.data.list.map((item, index) => {
          const id = item.id || item.value || item.sysDictionaryDetailID || index + 1;
          const label = item.label || item.value || item.name || `学校${index + 1}`;
          return {
            text: label,
            value: parseInt(id) || index + 1,
          };
        });
      } else {
        schoolOptions.value = [];
      }
    } catch (e) {
      console.warn('获取学校列表失败:', e);
      uni.showToast({ title: '获取学校列表失败', icon: 'none' });
      schoolOptions.value = [];
    }
  };

  // 获取专业列表
  const fetchMajors = async () => {
    try {
      const response = await get('/sysDictionaryDetail/getSysDictionaryDetailTree', {
        page: 1,
        pageSize: 200,
        sysDictionaryID: 9,
      });

      if (response && response.code === 0 && Array.isArray(response.data)) {
        majorOptions.value = response.data.map((item, index) => {
          const id = item.id || item.value || item.sysDictionaryDetailID || index + 1;
          const label = item.label || item.value || item.name || `专业${index + 1}`;
          return {
            text: label,
            value: parseInt(id) || index + 1,
          };
        });
      } else {
        majorOptions.value = [];
      }
    } catch (e) {
      console.warn('获取专业列表失败:', e);
      uni.showToast({ title: '获取专业列表失败', icon: 'none' });
      majorOptions.value = [];
    }
  };

  // 获取年级列表
  const fetchGrades = async () => {
    try {
      const response = await get('/sysDictionaryDetail/getSysDictionaryDetailList', {
        page: 1,
        pageSize: 200,
        sysDictionaryID: 7,
      });

      if (response && response.code === 0 && Array.isArray(response.data?.list)) {
        gradeOptions.value = response.data.list.map((item, index) => {
          const id = item.id || item.value || item.sysDictionaryDetailID || index + 1;
          const label = item.label || item.value || item.name || `年级${index + 1}`;
          return {
            text: label,
            value: parseInt(id) || index + 1,
          };
        });
      } else {
        gradeOptions.value = [];
      }
    } catch (e) {
      console.warn('获取年级列表失败:', e);
      uni.showToast({ title: '获取年级列表失败', icon: 'none' });
      gradeOptions.value = [];
    }
  };

  // 获取学历列表
  const fetchEducations = async () => {
    try {
      const response = await get('/sysDictionaryDetail/getSysDictionaryDetailList', {
        page: 1,
        pageSize: 200,
        sysDictionaryID: 8,
      });

      if (response && response.code === 0 && Array.isArray(response.data?.list)) {
        educationOptions.value = response.data.list.map((item, index) => {
          const id = item.id || item.value || item.sysDictionaryDetailID || index + 1;
          const label = item.label || item.value || item.name || `学历${index + 1}`;
          return {
            text: label,
            value: parseInt(id) || index + 1,
          };
        });
      } else {
        educationOptions.value = [];
      }
    } catch (e) {
      console.warn('获取学历列表失败:', e);
      uni.showToast({ title: '获取学历列表失败', icon: 'none' });
      educationOptions.value = [];
    }
  };

  const changeAvatar = () => {
    uni.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      success: res => {
        const temp = res.tempFilePaths?.[0] || res.tempFiles?.[0]?.path;
        if (!temp) return;
        uni.showLoading({ title: '处理中', mask: true });
        uni.compressImage({
          src: temp,
          quality: 80,
          success: cr => toBase64(cr.tempFilePath),
          fail: () => toBase64(temp),
        });
      },
    });
  };
  // 将图片转为base64
  const toBase64 = filePath => {
    try {
      const fs = uni.getFileSystemManager && uni.getFileSystemManager();
      if (!fs || !fs.readFile) {
        uni.hideLoading();
        uni.showToast({ title: '不支持读取文件', icon: 'none' });
        return;
      }
      fs.readFile({
        filePath,
        encoding: 'base64',
        success: r => {
          form.value.headerImg = 'data:image/jpeg;base64,' + r.data;
          uni.hideLoading();
        },
        fail: () => {
          uni.hideLoading();
          uni.showToast({ title: '处理失败', icon: 'none' });
        },
      });
    } catch (e) {
      console.warn('toBase64 error:', e);
      uni.hideLoading();
      uni.showToast({ title: '处理失败', icon: 'none' });
    }
  };

  // 显示保存确认弹窗
  const showSaveDialog = () => {
    uni.showModal({
      title: '保存确认',
      content: '是否保存修改？',
      confirmText: '保存',
      cancelText: '取消',
      success: res => {
        if (res.confirm) {
          save();
        }
      },
    });
  };

  const save = async () => {
    if (saving.value) return;
    if (!form.value.nickName) {
      uni.showToast({ title: '请输入昵称', icon: 'none' });
      return;
    }

    // 添加更多字段验证
    if (form.value.nickName.length < 2) {
      uni.showToast({ title: '昵称至少需要2个字符', icon: 'none' });
      return;
    }

    if (!form.value.school) {
      uni.showToast({ title: '请选择学校', icon: 'none' });
      return;
    }

    if (!form.value.grade) {
      uni.showToast({ title: '请选择年级', icon: 'none' });
      return;
    }

    if (!form.value.major) {
      uni.showToast({ title: '请选择专业', icon: 'none' });
      return;
    }

    if (!form.value.education) {
      uni.showToast({ title: '请选择学历', icon: 'none' });
      return;
    }

    if (form.value.phone && !/^1[3-9]\d{9}$/.test(form.value.phone)) {
      uni.showToast({ title: '请输入正确的手机号格式', icon: 'none' });
      return;
    }

    if (form.value.email && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(form.value.email)) {
      uni.showToast({ title: '请输入正确的邮箱格式', icon: 'none' });
      return;
    }
    saving.value = true;
    try {
      // 清理数据：将空字符串转为 null 或删除
      const cleanData = { ...form.value };

      // 处理可能的空字符串字段
      Object.keys(cleanData).forEach(key => {
        if (cleanData[key] === '' || cleanData[key] === null || cleanData[key] === undefined) {
          delete cleanData[key]; // 删除空字段
        }
      });

      // 构建包含所有必传字段的数据（避免重复字段）
      const basicData = {
        // 必传字段
        id: cleanData.id || uni.getStorageSync('userId') || 1,
        nickName: cleanData.nickName,
        phone: cleanData.phone || '',
        email: cleanData.email || '240305619@qq.com',
        headerImg: cleanData.headerImg || '',
        grade: cleanData.grade,
        school: cleanData.school,
        major: cleanData.major,
        education: cleanData.education,
        signature: cleanData.signature || '',
      };

      // 最终清理：创建一个全新的干净对象
      const finalData = {
        id: basicData.id,
        nickName: basicData.nickName,
        phone: basicData.phone,
        email: basicData.email,
        headerImg: basicData.headerImg,
        grade: basicData.grade,
        school: basicData.school,
        major: basicData.major,
        education: basicData.education,
        signature: basicData.signature,
      };

      // 调用真实的后端接口
      const result = await put('/c/user/setSelfInfo', finalData);

      // 检查业务状态码
      if (result.code !== 0) {
        // 业务失败
        console.error('保存失败，业务错误:', result);

        // 显示详细错误信息
        let errorMsg = result.msg || '保存失败';
        if (result.code === 7) {
          errorMsg += ' (可能是数据验证失败)';
        }

        uni.showToast({
          title: errorMsg,
          icon: 'none',
          duration: 4000,
        });
        return; // 直接返回，不执行后续逻辑
      }

      // 同时更新本地存储，供me页面使用
      const currentUserInfo = uni.getStorageSync('userInfo') || {};
      const updatedUserInfo = {
        ...currentUserInfo,
        ...form.value,
        updateTime: new Date().toISOString(),
      };

      uni.setStorageSync('userInfo', updatedUserInfo);

      // 通过事件总线通知me页面用户信息已更新
      const eventData = {
        type: 'success',
        message: '个人资料更新成功',
        data: updatedUserInfo,
      };

      uni.$emit('userInfoUpdated', eventData);

      uni.showToast({ title: '保存成功', icon: 'success' });

      setTimeout(() => {
        uni.navigateBack();
      }, 1000);
    } catch (e) {
      console.error('save error:', e);
      uni.showToast({ title: '保存失败，请稍后重试', icon: 'none' });
    } finally {
      saving.value = false;
    }
  };
</script>
<style lang="scss" scoped>
  .page {
    min-height: 100vh;
    background: #f5f6fa;
    padding: 40rpx 20rpx 140rpx 20rpx;
  }

  .avatar-cell {
    display: flex;
    justify-content: flex-end;
    align-items: center;
    width: 100%;
  }

  .card {
    margin-bottom: 20rpx;
    background: #fff;
    border-radius: 16rpx;
    box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.03);
    overflow: hidden;
  }

  .footer {
    position: fixed;
    left: 0;
    right: 0;
    bottom: env(safe-area-inset-bottom);
    padding: 20rpx;
    background: #fff;
    box-shadow: 0 -6rpx 12rpx rgba(0, 0, 0, 0.04);
    z-index: 999;
  }

  /* 固定宽度标题列，保证对齐 */
  .title-fixed {
    width: 160rpx;
    /* 更宽的标题列，右侧内容能靠左展示 */
    color: #333;
    font-size: 32rpx;
    font-weight: 500;
  }

  /* 选择器显示值的通用样式 */
  .cell-value {
    width: 100%;
    text-align: center;
    padding-left: 10rpx;
    font-size: 32rpx;
  }

  .cell-value--placeholder {
    color: #c0c4cc;
  }

  .cell-value--filled {
    color: #333;
  }
</style>
